﻿#nullable enable

using System;
using System.Linq;

namespace PHMEE.EnergyEfficiency;

[AttributeUsage(AttributeTargets.Property, AllowMultiple = false)]
public class FloatRoundAttribute : Attribute
{
    public int DecimalPlaces { get; }

    public FloatRoundAttribute(int decimalPlaces)
    {
        DecimalPlaces = decimalPlaces;
    }
}

public static class FloatRoundHelper
{
    public static void RoundProperties(object obj)
    {
        var properties = obj.GetType().GetProperties().Where(
            prop => Attribute.IsDefined(prop, typeof(FloatRoundAttribute)) && 
                    (prop.PropertyType == typeof(float) || prop.PropertyType == typeof(float?)));

        foreach (var property in properties)
        {
            var value = property.GetValue(obj);
            if (value != null) // Check if the value is not null
            {
                float floatValue = (float)value;
                if (property.GetCustomAttributes(typeof(FloatRoundAttribute), false).FirstOrDefault() is FloatRoundAttribute attribute)
                {
                    float roundedValue = (float)Math.Round(floatValue, attribute.DecimalPlaces, MidpointRounding.AwayFromZero);
                    property.SetValue(obj, roundedValue);
                }
            }
        }
    }
}